package com.qzsf.backend.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qzsf.backend.common.Result;
import com.qzsf.backend.dto.ForgetRequest;
import com.qzsf.backend.dto.LoginRequest;
import com.qzsf.backend.dto.UserDetailDTO;
import com.qzsf.backend.entity.UserAuth;
import com.qzsf.backend.entity.UserProfile;
import com.qzsf.backend.mapper.UserAuthMapper;
import com.qzsf.backend.mapper.UserProfileMapper;
import com.qzsf.backend.service.UserService;
import com.qzsf.backend.util.JwtUtil;
import com.qzsf.backend.util.Sha256Util;
import com.qzsf.backend.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Year;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
 * @Author: Dennis Chen
 * @CreateTime: 2024/10/30 16:51 周三
 * @Email 1429278462@qq.com
 * @Remark 用户服务层实现类
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserProfileMapper userProfileMapper;
    @Override
    public Result login(LoginRequest loginRequest) {
        UserAuth userAuth = userAuthMapper.findByUsername(loginRequest.getUsername());
        if(userAuth == null){
            return Result.error("该账号不存在");
        }
        if (userAuth.getStatus() == 0){
            return Result.error("该账号处于不可用状态");
        }
        if(userAuth.getPassword().equals(Sha256Util.getSHA256String(loginRequest.getPassword()))){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",userAuth.getId());
            claims.put("username",userAuth.getUsername());
            claims.put("role",userAuth.getRole().name());
            String token = JwtUtil.genToken(claims);
            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }else{
            return Result.error("密码错误");
        }
    }

    @Override
    public Result info() {
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");

        UserAuth userAuth = userAuthMapper.findByUsername(username);
        return Result.success(userAuth);
    }

    @Override
    public Result quit(String token) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

    @Override
    public Result createUser(UserDetailDTO userDetailDto) {
        String username = userDetailDto.getUsername();
        UserAuth confirmUser = userAuthMapper.findByUsername(username);
        if(confirmUser!=null){
            return Result.error("当前账号已存在");
        }
        UserAuth userAuth = new UserAuth(userDetailDto);
        String sha256String = Sha256Util.getSHA256String(userAuth.getPassword());
        userAuth.setPassword(sha256String);
        userAuthMapper.createUserAuth(userAuth);
        int id = userAuthMapper.findByUsername(userAuth.getUsername()).getId();
        UserProfile userProfile = new UserProfile(id,userDetailDto);
        userProfileMapper.createUserProfile(userProfile);
        return Result.success();
    }

    @Override
    public Result deleteUser(int id) {
        if(userAuthMapper.deleteUserAuth(id)>0){
            return Result.success();
        }else{
            return Result.error("删除异常");
        }
    }

    @Override
    public Result updateUser(UserProfile userProfile) {
        if(userProfileMapper.getUserProfileById(userProfile.getId())==null){
            //todo 这边创建的时候没有传入正确的id
            userProfileMapper.createUserProfile(userProfile);
        }else {
            userProfileMapper.updateUserProfile(userProfile);
        }
        return Result.success();
    }

    @Override
    public Result getAllUserDetail(String name, Year enrollmentYear, String faculty, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<UserDetailDTO> userDetailDTOList;
        String year = "";
        if(!name.isEmpty()||enrollmentYear!=null||!faculty.isEmpty()){
            if(enrollmentYear!=null){
                year = enrollmentYear.toString();
            }
            userDetailDTOList = userProfileMapper.getAllUserDetailByNameOrYear(name, year,faculty);
        }else {
            userDetailDTOList = userProfileMapper.getAllUserDetail();
        }
        if(userDetailDTOList == null){
            return Result.error("查询数据为空");
        }else{
            return Result.success(new PageInfo<>(userDetailDTOList));
        }
    }


    @Override
    public Result getUserProfile(int id) {
        UserProfile userProfile = userProfileMapper.getUserProfileById(id);
        if(userProfile == null){
            return Result.error("没有此条记录");
        }else{
            return Result.success(userProfile);
        }
    }

    @Override
    public Result getUserRole() {
        Map<String,Object> map = ThreadLocalUtil.get();
        String role = (String) map.get("role");
        return Result.success(role);
    }

    @Override
    public Result forget(ForgetRequest forgetRequest) {
        UserAuth userAuth = userAuthMapper.getUserByName(forgetRequest.getUsername());
        int id = userAuth.getId();
        UserProfile userProfile = userProfileMapper.getUserProfileById(id);
        String email = forgetRequest.getEmail();
        if(!userProfile.getEmail().equals(email)){
            return Result.error("该账户绑定的邮箱不是此邮箱");
        }
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String code = operations.get(email);
        if(code == null){
            return Result.error("验证码填写错误");
        }
        if(!code.trim().equals(forgetRequest.getCode().trim())){
            System.out.println(code);
            System.out.println(forgetRequest.getCode());
            return Result.error("验证码填写错误");
        }
        operations.getOperations().delete(email);
        String sha256String = Sha256Util.getSHA256String(forgetRequest.getNewPassword());
        if(userAuthMapper.forgetPassword(forgetRequest.getUsername(), sha256String)>0){
            return Result.success();
        }else{
            return Result.error("修改失败");
        }
    }

    @Override
    public Result getUserBasicProfile() {
        Map<String,Object> map = ThreadLocalUtil.get();
        int id = (int) map.get("id");
        return Result.success(userProfileMapper.getMobileUserProfile(id));
    }
}
